var fs = require('fs');

module.exports = {
    save: function(list, nameInfo, cb) {
        if (!((typeof list) === 'object' && list.length > 0)) {
            list = [list];
        }
        var name = [];

        save(list, nameInfo, name, function() {
            cb(name);
        });
    }
};

function save(list, nameInfo, nameList, cb) {
    if (list.length === 0) {
        return cb();
    }
    var file = list.pop();
    if (file === undefined) {
        return save(list, nameInfo, nameList, cb);
    }

    var base64Data = file.replace(/^data:image\/.*;base64,/, "");
    var dataBuffer = new Buffer(base64Data, 'base64');
    var name = '/upload/' + Date.now();
    for (var i in nameInfo) {
        name += '@' + i + '-' + nameInfo[i] + '@';
    }
    name += Math.floor(Math.random() * 100);
    name += '.png';
    fs.writeFile(CONFIG.publicDIR + name, dataBuffer, function(err) {
        if (err) {
            console.log(err);
            return cb();
        } else {
            nameList.unshift(CONFIG.site + name);
            save(list, nameInfo, nameList, cb);
        }
    });
}